layui.use(['form', 'layer'], function () {
    var form = layui.form();
    var layer = layui.layer;
    var $ = layui.jquery;

    var captchaImg = $('.captcha');
    var checkUser = $('.a-left');

    var updateCaptcha = function () {
        captchaImg.prop('src', '/captcha/image?v=' + Math.random());
    };

    updateCaptcha();

    captchaImg.click(function () {
        updateCaptcha();
    });

    checkUser.click(function () {
        var usernameInput = $('#username').val();
        console.log(usernameInput);
        if ("" === usernameInput) {
            layer.open({title: '警告', content: '您需要一个用户名！'});
        } else {
            $.post('register/checkUser', {"username": usernameInput}, function (data) {

                if (data.status) {
                    layer.open({title: '警告', content: '用户名已存在'});
                    document.getElementById("username-status").innerHTML = "<i class=\"layui-icon\" style=\"color: #FF5722\">&#x1007;</i>";
                } else {
                    layer.open({title: '警告', content: '用户名可以使用'});
                    document.getElementById("username-status").innerHTML = "<i class=\"layui-icon\" style=\"color: #70ED3A;\">&#xe610;</i>";
                }
            })
        }
    });

    form.on('submit(registerSubmit)', function (data) {
        var test = eval(data.field);
        if (test.pwd === test.salt) {
            $.post('register/register', data.field, function (data) {
                if (!data.status) {
                    layer.open({title: '警告', content: data.msg});
                    updateCaptcha();
                } else {
                    location.href = '/register/success';
                }
            })
        } else {
            layer.open({title: '警告', content: '两次密码输入不一致'});
            updateCaptcha();
        }
        return false;
    });



});